package com.server.service.impl;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.server.common.base.PathManager;
import com.server.date.DateType;
import com.server.date.DateUtil;
import com.server.service.IAttachmentService;
import com.server.service.ICommonDataService;
import com.server.web.DataVector;
import com.server.web.RequestInput;

@Service("AttachmentService")
public class AttachmentService implements IAttachmentService {
	
	private static final String tableName = "education.file";
	
	@Autowired
	private JdbcTemplate jdbcTemplate;
	@Autowired
	private ICommonDataService commonDataService;
	
	@Override
	public Boolean add(String operator,String actionType,
			Integer actionId,Map<String, Object> inputMap){
		if (StringUtils.isEmpty(operator) || StringUtils.isEmpty(actionType)
			|| actionId == null || inputMap == null) {
			return false;
		}
		inputMap.put("actionType", actionType);
		inputMap.put("actionId", actionId);
		return commonDataService.add(operator, tableName, inputMap);
	}
	@Override
	public Boolean update(String operator,String id,
			Map<String, Object> inputMap){
		if (StringUtils.isEmpty(operator)
				|| id == null || inputMap == null) {
			return false;
		}
		inputMap.put("mender", operator);
		return commonDataService.update(operator, tableName, "id", id, inputMap);
	}
	/**
	 * 状态设为删除
	 * @param ids
	 * @return
	 * @author ServerZhang
	 * @date 2016年7月18日
	 */
	@Override
	public Integer deleteAll(String ids){
		StringBuffer sqlBuffer = new StringBuffer();
		String dateStr = DateUtil.getDateStr(new Date(),DateType.YYYY_MM_DD_HH_mm_ss_SSS);
		sqlBuffer.append("Update ").append(tableName)
			.append(" set deleted=1,updateTime='").append(dateStr)
			.append("' where id in('")
			.append(ids.replaceAll(",", "','")).append("')");
		return jdbcTemplate.update(sqlBuffer.toString());
	}
	@Override
	public Integer removeAll(String ids){
		StringBuffer sqlBuffer = new StringBuffer();
		sqlBuffer.append("Delete from ").append(tableName)
			.append(" where id in('")
			.append(ids.replaceAll(",", "','")).append("')");
		return jdbcTemplate.update(sqlBuffer.toString());
	}
	@Override
	public DataVector<Map<String, Object>> getList(String actionType,
			Integer actionId,Boolean containDeleted,RequestInput requestInput){
		StringBuffer whereBuffer = new StringBuffer();
		whereBuffer.append("actionType='").append(actionType)
			.append("' and actionId=").append(actionId);
		if (containDeleted == null ||  !containDeleted) {
			whereBuffer.append(" and deleted=0");
		}
		String sortStr = "createTime desc";
		return commonDataService.getListData(tableName, whereBuffer.toString(), sortStr, requestInput);
	}
	@Override
	public List<Map<String, Object>> getList(String actionType,
			String actionIds){
		if (StringUtils.isEmpty(actionType) || StringUtils.isEmpty(actionIds)) {
			return new ArrayList<Map<String,Object>>();
		}
		String sql = "Select * from education.file where actionType='%s' and actionId in ('%s') order by createTime desc";
		return jdbcTemplate.queryForList(String.format(sql, actionType,actionIds.replaceAll(",", "','")));
	}
	@Override
	public Map<String, Object> getForm(Integer id){
		return commonDataService.getFormData(tableName, "id", id.toString(), null, null);
	}
	 /**
	 * 清除附件记录并从服务器上删除文件
	 * @param id
	 * @return
	 * @author ServerZhang
	 * @date 2016年7月20日
	 */
	@Override
	public Integer clear(String ids){
		StringBuffer sqlBuffer = new StringBuffer("Select * from ");
		sqlBuffer.append(tableName).append(" where id in('")
			.append(ids.replaceAll(",", "','")).append("')");
		List<Map<String, Object>> list = jdbcTemplate.queryForList(sqlBuffer.toString());
		Iterator<Map<String, Object>> iterator = list.iterator();
		while(iterator.hasNext()){
			Map<String, Object> form = iterator.next();
			if (form.size() > 0) {
				Object pathObj = form.get("filePath");
				Object uuidObj = form.get("uuid");
				if (pathObj != null && uuidObj != null) {
					String path = pathObj.toString()+"/"+uuidObj.toString();
					//删除文件
					new File(path).delete();
				}
			}
		}
		//删除记录
		return this.removeAll(ids);
	}
	@Override
	public Integer clear(String actionIds,String actionType){
		if (StringUtils.isEmpty(actionIds) || StringUtils.isEmpty(actionIds)) {
			return 0;
		}
		StringBuffer sqlBuffer = new StringBuffer("Select * from ");
		sqlBuffer.append(tableName).append(" where actionId in('")
			.append(actionIds.replaceAll(",", "','")).append("') and actionType='")
			.append(actionType).append("'");
		List<Map<String, Object>> list = jdbcTemplate.queryForList(sqlBuffer.toString());
		Iterator<Map<String, Object>> iterator = list.iterator();
		StringBuffer idsBuffer = new StringBuffer();
		while(iterator.hasNext()){
			Map<String, Object> form = iterator.next();
			if (form.size() > 0) {
				Object pathObj = form.get("filePath");
				Object uuidObj = form.get("uuid");
				Object idObj = form.get("id");
				if (pathObj != null && uuidObj != null) {
					String path = pathObj.toString()+"/"+uuidObj.toString();
					//删除文件
					new File(path).delete();
				}
				if (idObj != null) {
					if (idsBuffer.length() > 0) {
						idsBuffer.append(",");
					}
					idsBuffer.append(idObj.toString());
				}
			}
		}
		//删除记录
		return this.removeAll(idsBuffer.toString());
	}
}
